import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { Helmet, useModel, history } from '@umijs/max';
import { login } from "./service";
import Settings, { backgroundColor, color } from "../../../../config/defaultSettings";
import styles from "./index.less";
import { md516 } from "../../../utils/md5.js";
import { encode } from "../../../utils/encrypt";
import storage from "../../../utils/storage";
import { TYPE } from "../../types";
import { render } from "@/app";

export default () => {
  // 若已经登录，则跳转到首页。
  if (storage.getData().token.length === 14) {
    history.replace({ pathname: "/welcomeYou" });
    return;
  }

  const { setInitialState } = useModel("@@initialState");

  const submit = async (formData: TYPE.LoginParams) => {
    const res = await login({
      ...formData,
      password: md516(formData.password),
    });

    let data: TYPE.Data = res.data;
    const route: TYPE.RouteItem[] = []; // 渲染后的路由数据
    const menuData: TYPE.MenuItem[] = []; // 主菜单，pid=0
    const childData: TYPE.MenuItem[] = []; // 子菜单，pid>0

    // 分出主菜单和子菜单(二级)
    data.menu.map(item => {
      const { pid } = item;
      if (pid) childData.push(item); // 子菜单
      else menuData.push(item); // 主菜单
    });

    // 建立从属关系
    menuData.map(item => {
      const { name, path, icon } = item;
      const routeItem: TYPE.RouteItem = { name, path };

      if (icon) routeItem.icon = icon;

      childData.map(child => {
        if (child.pid === item.id) {
          const { name } = child;
          if (!routeItem.children) routeItem.children = [];
          routeItem.children.push({
            name, path: child.path, element: path + "/" + child.path,
          });
        }
      });

      if (!routeItem.children) routeItem.element = path;
      route.push(routeItem);
    });

    // 生成权限凭据字符串
    const accessData = data.res.map(({ path }) => path).toString();

    let { token, user } = data;
    token = encode(token);
    data = { ...data, token, route, accessData };
    storage.setData(data);

    render(storage.oldRender, route);
    setInitialState(() => ({ loading: false, token, user, accessData }));
  };

  return (
    <>
      <Helmet>
        <title>用户登录</title>
      </Helmet>
      <div className={styles.container} style={{ backgroundColor, color }}>
        <div className={styles.content}>
          <LoginForm
            title={Settings.title}
            logo={<img alt="logo" src="/logo.png" />}
            contentStyle={{ paddingTop: 40, minWidth: 280, maxWidth: "75vw" }}
            onFinish={(formData: TYPE.LoginParams) => submit(formData)}>
            <ProFormText
              name="username"
              placeholder="用户名"
              rules={[{ required: true, message: "请输入用户名" }]}
              fieldProps={{
                maxLength: 20,
                size: "large",
                prefix: <UserOutlined />,
                autoComplete: "new-password",
                style: { backgroundColor, color },
              }}
            />
            <ProFormText.Password
              name="password"
              placeholder="密码"
              rules={[{ required: true, message: "请输入登录密码" }]}
              fieldProps={{
                maxLength: 20,
                size: "large",
                prefix: <LockOutlined />,
                autoComplete: "new-password",
                style: { backgroundColor, color },
              }}
            />
          </LoginForm>
        </div>
      </div>
    </>
  );
};
